package com.feizhi.inventory.fragment.Inventorydetails.waitinventoryfragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.aserbao.aserbaosandroid.functions.database.greenDao.db.DaoSession;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDetailsDao;
import com.feizhi.inventory.MainActivity;
import com.feizhi.inventory.R;
import com.feizhi.inventory.database.TaskDetails;
import com.feizhi.inventory.database.dbApp;
import com.feizhi.inventory.databinding.FragmentInventoryRecyclerBinding;
import com.feizhi.inventory.fragment.Inventorydetails.WaitInventoryAdapter;
import com.feizhi.inventory.util.ThreadPool;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

/**
 *  等待盘点
 * */
public class WaitInventoryFragment extends Fragment {

    private TaskDetailsDao taskDetailsDao;
    List<TaskDetails> taskDetailsList = new ArrayList<>();
    List<TaskDetails> lists, saoCodeList, rfidList;
    String  taskID;

//    private TaskDetailsMyAdapter adapter;
    private WaitInventoryAdapter adapter;
    private FragmentInventoryRecyclerBinding mBinding;
    private MainActivity mActivity;

    private String sao_code;
    private DaoSession updaoSession;

    public WaitInventoryFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (MainActivity) getActivity();
        updaoSession = ((dbApp) mActivity.getApplication()).getDaoSession();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mBinding = FragmentInventoryRecyclerBinding.inflate(inflater);
        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        setOnClickListener();
    }

    private void setOnClickListener() {

        adapter.setItemOnClickListener(new WaitInventoryAdapter.OnClickListener() {
            @Override
            public void OnItemClickListener(int position) {

                Bundle bundle = new Bundle();
                bundle.putString("id", taskDetailsList.get(position).getId());
                bundle.putString("name", taskDetailsList.get(position).getName());
                bundle.putString("spec", taskDetailsList.get(position).getSpec());
                bundle.putString("eps_id", taskDetailsList.get(position).getEpcID());
                bundle.putString("save_place", taskDetailsList.get(position).getSavePlace());
                bundle.putString("custodian", taskDetailsList.get(position).getCustodian());
                bundle.putString("department", taskDetailsList.get(position).getDepartment());
                bundle.putString("state", taskDetailsList.get(position).getState());
                bundle.putString("notes_1", taskDetailsList.get(position).getNotes_1());
                bundle.putString("notes_2", taskDetailsList.get(position).getNotes_2());
                bundle.putString("notes_3", taskDetailsList.get(position).getNotes_3());
                bundle.putString("type", taskDetailsList.get(position).getType());
                bundle.putString("inputDate", taskDetailsList.get(position).getInputDate());
                Navigation.findNavController(mActivity, R.id.fragment_my).navigate(R.id.itemDetailsFragment, bundle);

            }
        });

    }

    private void initView() {
        LiveEventBus.get().with("search_condition2", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                saoCodeList = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(taskID),
                        TaskDetailsDao.Properties.State.eq("未盘点")).list();
                List<TaskDetails> condition = new ArrayList<>();
                taskDetailsList.clear();
                for (int i = 0; i < saoCodeList.size(); i++) {

                    if (saoCodeList.get(i).getName().contains(s)) {
                        taskDetailsList.add(saoCodeList.get(i));
                    }

                }
                int mateSize = taskDetailsList.size();
                Toast.makeText(mActivity, "为您搜索到" + mateSize + "条数据", Toast.LENGTH_SHORT).show();
                adapter.setData(taskDetailsList);

            }
        });


        LiveEventBus.get().with("epc_id", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                DaoSession rfiddaoSession = ((dbApp) mActivity.getApplication()).getDaoSession();
                String ecpid = s;
                rfidList = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.like(taskID),TaskDetailsDao.Properties.EpcID.like(ecpid)).list();
                if (rfidList.size() == 0) {
                    Toast.makeText(mActivity, "该物品不在列表中", Toast.LENGTH_SHORT).show();
                }else {
                    String sql = "update "+rfiddaoSession.getTaskDetailsDao().getTablename()+" set "+TaskDetailsDao.Properties.State.columnName+"='已盘点' where "
                                            +TaskDetailsDao.Properties.TaskID.columnName+"='"+taskID+"' and "+TaskDetailsDao.Properties.EpcID.columnName+"='"+ecpid+"'";
                    rfiddaoSession.getDatabase().execSQL(sql);

                                    int len = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(taskID),TaskDetailsDao.Properties.State.eq("未盘点")).list().size();
                                    if (len == 0) {
                                        String taskSql = "update " + rfiddaoSession.getTaskDao().getTablename() + " set " + TaskDao.Properties.Task_state.columnName + "='已盘点' where "
                                                + TaskDao.Properties.Task_ID.columnName + "='" + taskID + "'";
                                        rfiddaoSession.getDatabase().execSQL(taskSql);

                                        Navigation.findNavController(mActivity, R.id.fragment_my).navigateUp();
                                    }
                }
            }
        });


        DaoSession daoSession =((dbApp) mActivity.getApplication()).getDaoSession();
        taskDetailsDao = daoSession.getTaskDetailsDao();

        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new WaitInventoryAdapter(taskDetailsList, mActivity);
        mBinding.recyclerView.setAdapter(adapter);
//



        LiveEventBus.get().with("Task_ID", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

                taskID = s;


                onRefresh();
            }
        });

        LiveEventBus.get().with("epcrfid",String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

                String rfid_epc = s;
                rfidList = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.EpcID.eq(s)).list();

                    String sql = "update " + updaoSession.getTaskDetailsDao().getTablename() + " set " + TaskDetailsDao.Properties.State.columnName + "='已盘点' where "
                            + TaskDetailsDao.Properties.TaskID.columnName + "='" + taskID + "' and " + TaskDetailsDao.Properties.EpcID.columnName + "='" + s + "'" +
                            " and " + TaskDetailsDao.Properties.State.columnName + "= '" + "未盘点" + "'";
                    updaoSession.getDatabase().execSQL(sql);



                    for (int i = 0; i < taskDetailsList.size(); i++) {
                        if (taskDetailsList.get(i).getEpcID().equals(s)) {
                            taskDetailsList.remove(i);
                            adapter.notifyDataSetChanged();
                        }
                    }


            }

        });

        LiveEventBus.get().with("scan_code", String.class).observe(this, new Observer<String>() {

            @Override
            public void onChanged(String s) {
                sao_code = s;

                if (TextUtils.isEmpty(sao_code)) {
                    return;
                }

                saoCodeList = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.like(taskID), TaskDetailsDao.Properties.EpcID.like(sao_code)).list();

                if (saoCodeList.isEmpty()) {
//                    Toast.makeText(mActivity, "该物品不在列表中", Toast.LENGTH_SHORT).show();
                } else {
                    String sql = "update " + updaoSession.getTaskDetailsDao().getTablename() + " set " + TaskDetailsDao.Properties.State.columnName + "='已盘点' where "
                            + TaskDetailsDao.Properties.TaskID.columnName + "='" + taskID + "' and " + TaskDetailsDao.Properties.EpcID.columnName + "='" + sao_code + "'";
                    updaoSession.getDatabase().execSQL(sql);

                    for (int i = 0; i < taskDetailsList.size(); i++) {
                        if (taskDetailsList.get(i).getEpcID().equals(sao_code)) {
                            taskDetailsList.remove(i);
                            adapter.notifyDataSetChanged();
                        }
                    }


                }
            }


        });


    }

    private void refresh() {

//        ProgressDialog progressDialog = new ProgressDialog(mActivity);
//        progressDialog.setTitle("加载数据");X
//        progressDialog.setMessage("正在加载ing...");
//        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        progressDialog.show();

        ThreadPool.runThread(() -> {

                lists = taskDetailsDao.queryBuilder().
                        where(TaskDetailsDao.
                                Properties.TaskID.like(taskID),
                                TaskDetailsDao.Properties.State.eq("未盘点")).list();

                //清空数据，防止重复
                if (!taskDetailsList.isEmpty()) {
                    taskDetailsList.clear();
                }
                taskDetailsList.addAll(lists);

                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.setData(taskDetailsList);
//                        progressDialog.dismiss();
                    }
                });

                taskDetailsDao.detachAll();

        });

    }

    public void onRefresh() {

        refresh();

    }

}